﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    public class Marquee : MonoBehaviour
    {
        public const float moveSpeed = 100;
        public Text text;

        public static Marquee instance;
        public static int CurrQueueCount
        {
            get { return queue.Count; }
        }
        public bool isPlaying { private set; get; }
        private static Queue<string> queue = new Queue<string>();
        private float maskWidth;

        public static void PushMsg(string msg)
        {
            queue.Enqueue(msg);
            if (instance)
            {
                instance.TryGetNewMsg();
            }
        }

        public void Awake()
        {
            instance = this;
            text.rectTransform.anchorMin = new Vector2(0, 0.5f);
            text.rectTransform.anchorMax = new Vector2(0, 0.5f);
            text.rectTransform.pivot = new Vector2(0, 0.5f);
            text.alignment = TextAnchor.MiddleLeft;
            text.horizontalOverflow = HorizontalWrapMode.Overflow;
            text.verticalOverflow = VerticalWrapMode.Overflow;
            ContentSizeFitter csf = GetComponent<ContentSizeFitter>();
            if (!csf) csf = text.gameObject.AddComponent<ContentSizeFitter>();
            csf.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
            csf.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
            maskWidth = (text.transform.parent as RectTransform).rect.width;
            Vector2 pos = text.rectTransform.anchoredPosition;
            pos.x = maskWidth;
            text.rectTransform.anchoredPosition = pos;

            for (int i = 0; i < 5; i++)
            {
                //AddMsg("正在体验中..." + i);
            }
        }

        private void TryGetNewMsg()
        {
            if (isPlaying) return; //一次只播放一条

            //开始获取新消息
            if (queue.Count > 0)
            {
                string msg = queue.Dequeue();
                text.text = msg;
                isPlaying = true;
            }
        }

        private void Update()
        {
            if (isPlaying)
            {
                Vector2 pos = text.rectTransform.anchoredPosition;
                pos.x -= moveSpeed * Time.deltaTime;
                if (pos.x + text.rectTransform.sizeDelta.x < 0)
                {
                    pos.x = maskWidth;
                    isPlaying = false;
                    TryGetNewMsg();
                }

                text.rectTransform.anchoredPosition = pos;
            }
        }

        private void OnDestroy()
        {
            instance = null;
        }
    }
}